/**
 * 
 */
package com.cp16.tss.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

import com.cp16.tss.dto.Service;

/**
 * @author ADMIN
 *
 */
public class ServiceDAO {

	SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

	public Service getServiceById(String serviceId) throws Exception {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.getTransaction().commit();
		Service service = (Service) session.get(Service.class, serviceId);
		session.close();
		return service;
	}
	
	public Service getServiceByName(String serviceName) throws Exception {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		@SuppressWarnings("unchecked")
		List<Service> serviceList = session.createCriteria( 
				Service.class).add(Restrictions.like("serviceName", serviceName)).list();
		Service service = null;
		if(serviceList.size() >0){
			service = serviceList.get(0);
		}
		session.getTransaction().commit();
		session.close();
		return service;
	}


	public boolean addService(Service service) throws Exception{
		try {
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			session.save(service);
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean updateService(Service service) throws Exception {
		Session session = sessionFactory.openSession();
		try {
			session.beginTransaction();
			session.update(service);
			session.getTransaction().commit();
			return true;
		} catch (HibernateException e) {
			session.getTransaction().rollback();
			e.printStackTrace();
			return false;
		} finally {
			session.clear();
			session.close();
		}
	}

	public boolean deleteService(Service service) throws Exception{
		try {
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			session.delete(service);
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public List<Service> getAllService() throws Exception {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Service.class);
		@SuppressWarnings("unchecked")
		List<Service> serviceList = criteria.list();
		session.getTransaction().commit();
		session.close();
		return serviceList;
	}
	
	public boolean checkServiceExist(String serviceId) throws Exception{
		Service service = getServiceById(serviceId);
		if (service != null) {
			return true;
		} else {
			return false;
		}
	}

}
